package com.we823.cms.controller.manage.cms;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.we823.cms.common.web.pageable.Direction;
import com.we823.cms.common.web.pageable.PageRequest;
import com.we823.cms.common.web.pageable.Sort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.we823.cms.common.WebConstants;
import com.we823.cms.common.json.model.JqgridModel;
import com.we823.cms.common.json.model.ZTreeModel;
import com.we823.cms.common.utils.RequestUtil;
import com.we823.cms.controller.manage.AbstractManageController;
import com.we823.cms.core.security.shiro.PermissionStatus;
import com.we823.cms.model.cms.Channel;
import com.we823.cms.repository.service.cms.ChannelService;

@Controller
@RequestMapping(WebConstants.WEB_PREFIX + WebConstants.WEB_MANAGE_URL + "/channel")
public class ChannelManageController extends AbstractManageController<Channel, Integer> {

	private String baseUrl = WebConstants.WEB_MANAGE_TEMPLATE_BaseUrl + "channel/";

	private ChannelService channelService;

	@Autowired
	public ChannelManageController(ChannelService channelService) {
		super(channelService);
		super.baseUrl = baseUrl;
		this.channelService = channelService;
		super.entityName="channel";
	}

	@Override
	public PageInfo<Channel> getData(PageRequest pageRequest, HttpServletRequest request, Model model, boolean pageable) {
		PageInfo<Channel> channelPage;
		Integer cattype = RequestUtil.getValueByName(request, "cattype", 0);
		if (cattype == 0) {
			if (pageable) {
				channelPage = channelService.findAll(pageRequest);
			} else {
				channelPage = new PageInfo<>(channelService.findAll());
			}
		} else {
			if(pageable){
				channelPage = channelService.findByType(cattype, pageRequest);
			}else{
				Sort sort = new Sort(Direction.ASC,"orderid");
				channelPage = new PageInfo<>(channelService.findByType(cattype, sort));
			}
		}
		return channelPage;
	}

	@RequestMapping("getChannels")
	@ResponseBody
	public Model getChannels(HttpServletRequest request, Model model) {
		check(PermissionStatus.VIEW);
		Integer id = RequestUtil.getValueByName(request, "id", -1);
		String pageable = RequestUtil.getValueByName(request, "pageable", "true");
		String action = RequestUtil.getValueByName(request, "action", "list");
		JqgridModel<Channel> jqgridModel = new JqgridModel<>(request, model);

		PageRequest pageRequest = super.getPageRequest(jqgridModel, request);

		PageInfo<Channel> channelModels = null;
		if ("true".equals(pageable)) {
			if ("get".equals(action)) {
				List<Channel> channels = new ArrayList<>();

				Channel channelModel = channelService.findOne(id);
				if (channelModel != null) {
					channels.add(channelModel);
				}
				channelModels = new PageInfo<>(channels);
			} else {
				if (id == -1) {
					channelModels = channelService.findAll(pageRequest);
				} else {
					Channel parent = channelService.findOne(id);
					channelModels = channelService.findByParent(parent, pageRequest);
				}
			}

		} else {
			Sort sort = getSort(request);
			if (id == -1) {
				channelModels = new PageInfo<>(channelService.findAll(sort));
			} else {
				Channel parent = channelService.findOne(id);
				channelModels = new PageInfo<>(channelService.findByParent(parent, sort));
			}
		}
		if (channelModels != null) {
			jqgridModel.setDatarows(channelModels.getList());
			jqgridModel.setRecords((int) channelModels.getTotal());
		}
		jqgridModel.flush();
		return model;
	}

	@RequestMapping("getChannelTree")
	@ResponseBody
	public Model getChannelTree(HttpServletRequest request, Model model) {
		check(PermissionStatus.VIEW);
		List<Channel> channels = null;
		Integer typeid = RequestUtil.getValueByName(request, "typeid", -1);
		if (typeid == null || typeid == -1) {
			channels = channelService.findAll(new Sort(Direction.ASC, "orderid"));
		} else {
			channels = channelService.findByType(1, new Sort(Direction.ASC, "orderid"));
		}

		List<ZTreeModel> zTreeModels = new ArrayList<ZTreeModel>();

		ZTreeModel zTreeModel = new ZTreeModel();
		zTreeModel.setName("一级栏目");
		zTreeModel.setId(0);
		zTreeModel.setpId(0);

		zTreeModels.add(zTreeModel);
		fillChannelTree(zTreeModels, channels);

		model.addAttribute("ztree", zTreeModels);
		return model;
	}

	@Override
	@RequestMapping("preEdit")
	public String preEdit(@RequestParam(value = "id", required = true, defaultValue = "0") Integer key, Model model) {
		check(PermissionStatus.VIEW);
		
		Channel channel = channelService.findOne(key);

		String parentName = "一级栏目";
		if (channel != null) {
			
			Channel parentChannelModel = channel.getParent();
			if (parentChannelModel != null) {
				parentName = parentChannelModel.getName();
			}

			model.addAttribute(super.entityName, channel);
			model.addAttribute("parentName", parentName);
		}

		return baseUrl + "preEdit";
	}

	@RequestMapping("sort")
	public String sort(Model model) {
		check(PermissionStatus.VIEW);
		return baseUrl + "sort";
	}

	@RequestMapping("saveSort")
	@ResponseBody
	public Model saveSort(HttpServletRequest request, Model model) {
		check(PermissionStatus.UPDATE);
		Map<String, Integer> orderids = Maps.newHashMap();
		Enumeration<String> names = request.getParameterNames();

		String isParent = RequestUtil.getValueByName(request, "isParent", "false");
		Integer currentId = RequestUtil.getValueByName(request, "current_id", 0);

		Integer success = 0;
		if (names != null && names.hasMoreElements()) {
			while (names.hasMoreElements()) {
				String name = names.nextElement();
				if (name.startsWith("orderid_")) {
					orderids.put(name, RequestUtil.getValueByName(request, name, 0));
				}
			}

			if (orderids.size()>0) {
				Set<String> ids = orderids.keySet();
				if (ids.size()>0) {
					for (String idString : ids) {
						Integer id = 0;
						String[] params = idString.split("_");
						if (params.length>0 && params.length == 2) {
							try {
								id = Integer.parseInt(params[1]);
							} catch (Exception ex) {
								id = 0;
							}
						}
						if (id != 0) {
							Integer orderid = orderids.get(idString);
							channelService.updateOrderidById(id, orderid);
						}
					}
				}
				success = 1;
			}
		}
		model.addAttribute("success", success);
		model.addAttribute("isParent", isParent);
		model.addAttribute("current_id", currentId);
		return model;
	}

	private void fillChannelTree(List<ZTreeModel> zTreeModels, List<Channel> channels) {
		if (channels != null) {
			ZTreeModel zTreeModel = null;
			for (Channel channelModel : channels) {
				zTreeModel = new ZTreeModel();
				zTreeModel.setId(channelModel.getId());
				int pId = (channelModel.getParent()==null) ? 0 : (channelModel.getParent().getId());
				zTreeModel.setpId(pId);
				zTreeModel.setName(channelModel.getName());
				List<Channel> childChannels = channelService.findByParent(channelModel, new Sort(Direction.ASC, "orderid"));
				if (childChannels != null && childChannels.size() > 0) {
					zTreeModel.setParent(false);
				} else {
					zTreeModel.setParent(true);
				}
				zTreeModels.add(zTreeModel);
			}
		}
	}

	@Override
	public void setIndetity() {
		setResourceIdentity("cms:channel");
	}

}
